<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点击 DIV 换色</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
          rel="stylesheet">
    <style>
        .item {
            width: 100px;
            height: 50px;
            border: solid 1px rgb(42, 156, 156);
            float: left;
            margin-right: 10px;
        }
    </style>
</head>

<body>
<div class="container">
    <h2 class="page-header">点击切换颜色</h2>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>
<script>
    // 获取所有的item
    let items = document.getElementsByClassName("item");

    // for (var i = 0; i < items.length; i++) { //使用var会出错，let块儿级作用域
    for (let i = 0; i < items.length; i++) {
        // 获取当前元素，绑定点击事件
        items[i].onclick = function (event) {
            // debugger
            // this.style.background = 'pink';
            items[i].style.background = 'pink';
        }
    }

</script>
</body>

</html>